import { ref } from 'vue'
import { supabase } from '../../lib/supabase'
import type { MovieSystemTags, SystemTagInfo } from './types'

export const useMovieTagOperations = () => {
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 为电影设置系统标签
  const setMovieSystemTags = async (
    movieId: number,
    tags: MovieSystemTags
  ): Promise<boolean> => {
    try {
      loading.value = true
      error.value = null

      // 确保数组格式正确
      const genreNames = tags.genres.length > 0 ? [...tags.genres] : null
      
      console.log('调用 set_movie_system_tags_simple，参数:', {
        p_movie_id: movieId,
        p_genre_names: genreNames,
        p_universe_name: tags.universe,
        p_language_name: tags.language,
        p_country_name: tags.country
      })

      const { data, error: fetchError } = await supabase
        .rpc('set_movie_system_tags_simple', {
          p_movie_id: movieId,
          p_genre_names: genreNames,
          p_universe_name: tags.universe,
          p_language_name: tags.language,
          p_country_name: tags.country
        })

      console.log('set_movie_system_tags_simple 响应:', { data, error: fetchError })

      if (fetchError) {
        console.error('数据库函数调用失败:', fetchError)
        error.value = fetchError.message
        return false
      }

      if (data && data.success) {
        console.log('标签设置成功:', data)
        return true
      } else {
        error.value = data?.error || '设置标签失败'
        console.error('标签设置失败:', data?.error)
        return false
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '设置标签失败'
      console.error('设置电影系统标签失败:', err)
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取电影的系统标签信息
  const getMovieSystemTags = async (movieId: number): Promise<SystemTagInfo[]> => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('get_movie_system_tags', { p_movie_id: movieId })

      if (fetchError) throw fetchError

      return data || []
    } catch (err) {
      console.error('获取电影系统标签失败:', err)
      return []
    }
  }

  // 从系统标签信息中提取简单的标签值
  const extractTagValues = (systemTags: SystemTagInfo[]): MovieSystemTags => {
    const result: MovieSystemTags = {
      genres: [],
      universe: null,
      language: null,
      country: null
    }

    systemTags.forEach(category => {
      switch (category.category_name) {
        case 'genre':
          result.genres = category.tag_names
          break
        case 'universe':
          result.universe = category.tag_names[0] || null
          break
        case 'language':
          result.language = category.tag_names[0] || null
          break
        case 'country':
          result.country = category.tag_names[0] || null
          break
      }
    })

    return result
  }

  // 批量添加电影标签
  const addMovieTagsBatch = async (movieId: number, tagIds: number[]) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('add_movie_tags_batch', { 
          p_movie_id: movieId,
          p_tag_ids: tagIds
        })

      if (fetchError) throw fetchError

      return data
    } catch (err) {
      console.error('批量添加电影标签失败:', err)
      throw err
    }
  }

  // 批量移除电影标签
  const removeMovieTagsBatch = async (movieId: number, tagIds: number[]) => {
    try {
      const { data, error: fetchError } = await supabase
        .rpc('remove_movie_tags_batch', { 
          p_movie_id: movieId,
          p_tag_ids: tagIds
        })

      if (fetchError) throw fetchError

      return data
    } catch (err) {
      console.error('批量移除电影标签失败:', err)
      throw err
    }
  }

  return {
    loading,
    error,
    setMovieSystemTags,
    getMovieSystemTags,
    extractTagValues,
    addMovieTagsBatch,
    removeMovieTagsBatch
  }
}
